const https = require('https');
const token = require('../createToken')
var {getUserQueryALL,getUserByPhone,addUser,delUser,updateUserAddress} = require('../db/useraction');
var {getScoreQueryALL,getScoreByPhone,addScoreTable,delScoreTable,updateScore} =require('../db/scoreaction');
/** //关于token
 *  HTTP是无状态的，并不记录用户身份，为了避免多次校验身份，需要在服务端生成一条包含用户信息的记录
 *  也就是session,再将这条记录发给用户并存储在用户本地，即cookie,接下来用户的请求都会带上这条cookie,若客户端的cookie与服务器的session能对应上，说明身份验证通过
 */
var _token = '4vjzZKCEhJM7WQGFBNmbitu8grfPq3H6DYIn1RTXcdes5kAV';
var key = 'gzxj_mWS^eM&20@sxC7sW';


var debugMode =true;
var jsonData=JSON.stringify({mobile:'18723356781',code:'123456',msg:'123456'});
function fn_checkUser(phone,callback){
    console.log('fn_checkUser-->> 进入用户查重 moblie:'+phone);
    getUserByPhone(phone,function(code){
        code.code = 102;
        console.log(code);
        if(code.requestData.length!=0){
            callback();
        }else if(code.requestData.length==0){
            //先注册
            fn_registerUser(phone,'',callback);
        }
    });
}

//注册没有用户地址！！！
function fn_registerUser(phone,address,callback){
    var params={phone:phone,address:address};
    addUser(params,function(code){
        if(code.request=='succeed'){
            addScoreTable(params.phone,function(code){
                code.describe =params.phone+':新用户添加成功';
                code.code = 106;
                console.log(code);
                callback();
            })
        }else{
            code.code = 106;
            console.log(code);
        }
    })
}


//接受客户端参数,u
var fn_reviceClientCode = async(ctx,next)=>{
    var _json = debugMode ? JSON.parse(jsonData) : JSON.parse(ctx.request.body);
    var mobile;
    var code;
    if(debugMode){
        mobile=_json.mobile; code = _json.code;
    }else{
        mobile = ctx.request.body.mobile;
        code = ctx.request.body.code;
    }
    var time = Math.round(new Date().getTime()/1000);
    var tok = token(mobile,code,time)
    var data = {mobile:mobile,code:code,time:time,token:tok};

    data = JSON.stringify(data);
    var url = 'https://fc.exijiu.cn/wx/public/index.php/api/sms/sendCode';
    fn_checkUser(mobile,function(){
        post(data,url);
    })
}

var fn_reviceClientCode_custom = async(ctx,next)=>{
    var _json = debugMode ? JSON.parse(jsonData) : JSON.parse(ctx.request.body);
    var mobile;
    var msg;
    if(debugMode){
        mobile=_json.mobile; msg = _json.msg;
    }else{
        mobile = ctx.request.body.mobile;
        msg = ctx.request.body.msg;
    }
    var tok = token(mobile,msg,time)
    var time = new Date().getTime();
    var data = {mobile:mobile,msg:msg,time:time,token:tok};
    
    data = JSON.stringify(data);
    var url = 'https://fc.exijiu.cn/wx/public/index.php/api/sms/sendMsg';
    fn_checkUser(mobile,function(){
        post(data,url);
    })
}

//检查回调信息
function checkMsg(chunk){
    var chunk =  JSON.parse(chunk);
    if(chunk.code)
    switch(chunk.code){
        case -1:
            console.log(chunk.code+"  "+chunk.msg);
            break;
        case 0:
            break;
    }
    return chunk;
}

function post(data,url){
    var opt = { 
        method: "POST", 
        port: 443, 
        host: 'fc.exijiu.cn',//可以用域名,ip地址 
        path: url, 
        data:data,
        headers: { 
         'Content-Type': 'application/json; charset=UTF-8' 
        }};
    
    var req = https.request(opt,function(res){
        console.log('STATUS: ' + res.statusCode); 
        console.log('HEADERS: ' + JSON.stringify(res.headers)); 
        res.setEncoding('utf8');  
        res.on('data', function (chunk) {  
            console.log('BODY: ' + chunk);  
            chunk = checkMsg(chunk);
        });  
    })
    req.on('error', function (e) { 
        console.log('problem with request: ' + e.message); 
       }); 
    req.write(data);//把请求发出去
    req.end();
}

var fn_sendCode = async(ctx,next)=>{
    ctx.response.body = `<h1>Index</h1>
    <form action="/API/110" method="post">
        <p>mobile: <input name="mobile" value="18723356781"></p>
        <p>code: <input name="code" value="123457"></p>
        <p><input type="submit" value="Submit"></p>
    </form>`;
}

var fn_csendCode = async(ctx,next)=>{
    ctx.response.body = `<h1>Index</h1>
    <form action="/API/111" method="post">
        <p>mobile: <input name="mobile" value="18723356781"></p>
        <p>msg: <input name="msg" value="123457"></p>
        <p><input type="submit" value="Submit"></p>
    </form>`;
}

module.exports = {
    'GET /API/sendCode': fn_sendCode,
    'GET /API/csendcode':fn_csendCode,
    'POST /API/110': fn_reviceClientCode,
    'POST /API/111':fn_reviceClientCode_custom
};